<!-- Tab.vue -->
<template>
  <div class="tabs" ref="tabsRef">
    <div class="tabs_wrap">
      <div class="tabs_nav" ref="tabsNavRef">
        <slot></slot>
        <div class="tab_line" :style="{ transform: tabLineTransform, width: tabLineWidth }"></div>
      </div>
    </div>
    <div class="tabs_content">
      <div class="tab__panel" v-for="(panel, index) in tabPanels" :key="index" v-show="currentIndex === index">
        <component v-for="(comp, i) in panel.content()" :is="comp" :key="i" />
      </div>
    </div>
  </div>
</template>

// Tab.vue
<script setup>
import { ref, computed, nextTick, watch, provide, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  modelValue: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['update:modelValue', 'tabchange'])

const currentIndex = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
    emit('tabchange', val)
  }
})

// 添加DOM引用
const tabsNavRef = ref(null)
const tabsRef = ref(null)

// ✅ 存储 tab 面板信息：label 和 content 函数（不是执行结果！）
const tabPanels = ref([])

// ✅ 注册 TabItem，content 传入的是一个函数
const registerTabItem = (tabItem) => {
  const index = tabPanels.value.length
  tabPanels.value.push({
    label: tabItem.label,
    // ✅ 保存 content 为函数，延迟执行
    content: tabItem.content, // 例如：() => slots.default()
    index
  })
  return index
}

const updateTabIndex = (index) => {
  currentIndex.value = index
}

// ✅ 下划线样式（保持不变）
const tabLineTransform = ref('translateX(0px)')
const tabLineWidth = ref('0px')

const updateTabLinePosition = () => {
  nextTick(() => {
    // 使用ref而不是全局查询
    const nav = tabsNavRef.value
    if (!nav) return
    
    // 在当前组件内查找tab项
    const tabItems = nav.querySelectorAll('.tab .tab__text--ellipsis')

    if (!tabItems.length || !tabItems[currentIndex.value]) return

    const activeTab = tabItems[currentIndex.value]
    const navRect = nav.getBoundingClientRect()
    const tabRect = activeTab.getBoundingClientRect()

    // 计算相对于导航容器的位置
    const left = tabRect.left - navRect.left
    const width = activeTab.offsetWidth

    // 确保下划线位置不会超出容器边界
    const maxLeft = navRect.width - width
    const adjustedLeft = Math.max(0, Math.min(left, maxLeft))

    tabLineTransform.value = `translateX(${adjustedLeft}px)`
    tabLineWidth.value = `${width}px`
  })
}

onMounted(() => {
  // 延迟执行，确保DOM完全渲染
  setTimeout(() => {
    updateTabLinePosition()
  }, 100)
  
  // 监听窗口大小变化
  window.addEventListener('resize', updateTabLinePosition)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', updateTabLinePosition)
})

watch(currentIndex, () => {
  updateTabLinePosition()
})

// ✅ 提供给子组件
provide('registerTabItem', registerTabItem)
provide('updateTabIndex', updateTabIndex)
provide('currentIndex', currentIndex)
</script>

<style lang="scss" scoped>
.tabs {
  position: relative;
  padding-bottom: 46px;
  display: flex;
  flex-direction: column;
  height: 100%;

  .tabs_wrap {
    overflow: hidden;
    height: 44px;

    .tabs_nav {
      height: 100%;
      padding-bottom: 15px;
      -webkit-user-select: none;
      user-select: none;
      display: flex;
      position: relative;
      box-sizing: content-box;

      .tab_line {
        position: absolute;
        bottom: 15px;
        left: 0;
        height: 3px;
        background-color: #39a9ed;
        border-radius: 3px;
        z-index: 1;
        transition: transform 0.3s ease-out, width 0.3s ease-out;
      }
    }
  }

  .tabs_content {
    flex: 1;
    overflow-y: auto;
    
    .tab__panel {
      width: 100%;
      height: 100%;
      // padding: 24px 20px;
    }
  }
}
</style>